import React, { useState, useEffect } from "react";
import {
  Modal,
  Typography,
  Space,
  Tag,
  Avatar,
  List,
  Button,
  Form,
  Input,
  message,
  Tooltip,
  Divider,
} from "antd";
import {
  UserOutlined,
  LikeOutlined,
  LikeFilled,
  RobotOutlined,
  SendOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionReply,
} from "../../../common/types/discussion";
import { useUser } from "../../../../contexts/UserContext";
import discussionService from "../../../../services/discussion";
import { AIService } from "../../../../services/ai";

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

// 根据用户角色生成默认头像
const getDefaultAvatar = (name: string, role: string) => {
  // 使用姓名的hash值作为种子，避免中文编码问题
  const hash = name.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0);
    return a & a;
  }, 0);
  const seed = Math.abs(hash).toString();
  
  // 根据角色设置不同的卡通头像样式
  if (role === "teacher") {
    // 教师使用更成熟的卡通风格
    return `https://api.dicebear.com/7.x/adventurer/svg?seed=${seed}&backgroundColor=b6e3f4`;
  } else {
    // 学生使用活泼的卡通风格
    return `https://api.dicebear.com/7.x/personas/svg?seed=${seed}&backgroundColor=ffdfbf`;
  }
};

interface DiscussionDetailProps {
  discussionId: string;
  onClose: () => void;
  likedDiscussions?: Set<string>;
  onLikeChange?: (discussionId: string, isLiked: boolean) => void;
}

const StyledModal = styled(Modal)`
  .ant-modal-body {
    max-height: 70vh;
    overflow-y: auto;
  }
`;

const ReplyList = styled(List<DiscussionReply>)`
  margin-top: 24px;
`;

const AIReply = styled.div`
  background: #f0f0ff;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
`;

const DiscussionDetail: React.FC<DiscussionDetailProps> = ({
  discussionId,
  onClose,
  likedDiscussions = new Set(),
  onLikeChange,
}) => {
  const { user } = useUser();
  const [discussion, setDiscussion] = useState<DiscussionPost>();
  const [loading, setLoading] = useState(true);
  const [aiLoading, setAiLoading] = useState(false);
  const [replyForm] = Form.useForm();
  const [aiService] = useState(new AIService());

  useEffect(() => {
    loadDiscussion();
  }, [discussionId]);

  const loadDiscussion = async () => {
    setLoading(true);
    try {
      // 使用静态数据
      const mockDiscussions: DiscussionPost[] = [
        {
          id: "1",
          title: "数据结构中链表和数组的区别是什么？",
          content: "在学习数据结构时，我对链表和数组的区别有些困惑。链表和数组在内存分配、访问效率、插入删除操作等方面有什么不同？希望有经验的同学能分享一下。",
          author: {
            id: "101",
            name: "李明华",
            role: "student",
            avatar: getDefaultAvatar("李明华", "student")
          },
          createTime: "2024-12-20 14:30:00",
          views: 156,
          likes: 23,
          replies: [
            {
              id: "r1",
              content: "链表和数组的主要区别在于内存分配方式。数组是连续存储，链表是离散存储。数组访问效率高但插入删除慢，链表相反。",
              author: {
                id: "201",
                name: "张伟",
                role: "teacher",
                avatar: getDefaultAvatar("张伟", "teacher")
              },
              createTime: "2024-12-20 15:15:00",
              likes: 15
            },
            {
              id: "r2",
              content: "补充一下，数组适合随机访问，链表适合频繁插入删除的场景。比如实现栈用数组，实现队列用链表。",
              author: {
                id: "102",
                name: "王雅琴",
                role: "student",
                avatar: getDefaultAvatar("王雅琴", "student")
              },
              createTime: "2024-12-20 16:20:00",
              likes: 8
            }
          ],
          tags: ["数据结构", "算法", "链表"],
          isPinned: true,
          aiResponse: {
            content: "链表和数组是两种基本的数据结构，它们在内存分配、访问方式、操作效率等方面有显著差异。\n\n**主要区别：**\n1. **内存分配**：数组连续存储，链表离散存储\n2. **访问效率**：数组O(1)随机访问，链表O(n)顺序访问\n3. **插入删除**：数组需要移动元素，链表只需修改指针\n4. **空间利用**：数组可能浪费空间，链表按需分配\n\n**应用场景：**\n- 数组：需要频繁随机访问的场景\n- 链表：需要频繁插入删除的场景",
            createTime: "2024-12-20 16:00:00"
          }
        },
        {
          id: "2",
          title: "数据库设计中的范式化问题",
          content: "在做数据库课程设计时，遇到了范式化的问题。第一范式、第二范式、第三范式分别是什么？在实际项目中如何平衡范式化和性能？",
          author: {
            id: "103",
            name: "陈志强",
            role: "student",
            avatar: getDefaultAvatar("陈志强", "student")
          },
          createTime: "2024-12-19 10:45:00",
          views: 89,
          likes: 12,
          replies: [
            {
              id: "r3",
              content: "范式化是为了减少数据冗余，但过度范式化会影响查询性能。一般建议到第三范式，特殊情况下可以适当反范式化。",
              author: {
                id: "202",
                name: "李雅琴",
                role: "teacher",
                avatar: getDefaultAvatar("李雅琴", "teacher")
              },
              createTime: "2024-12-19 11:30:00",
              likes: 18
            }
          ],
          tags: ["数据库", "设计", "范式"],
          isPinned: false,
          aiResponse: undefined
        },
        {
          id: "3",
          title: "TCP三次握手和四次挥手的理解",
          content: "计算机网络课程中学习了TCP协议，但对三次握手和四次挥手的过程还不是很清楚。谁能详细解释一下这个过程？",
          author: {
            id: "104",
            name: "刘梦华",
            role: "student",
            avatar: getDefaultAvatar("刘梦华", "student")
          },
          createTime: "2024-12-18 16:20:00",
          views: 234,
          likes: 31,
          replies: [
            {
              id: "r4",
              content: "三次握手：SYN→SYN+ACK→ACK，确保双方都有发送和接收能力。四次挥手：FIN→ACK→FIN→ACK，确保数据完全传输完毕。",
              author: {
                id: "203",
                name: "王建国",
                role: "teacher",
                avatar: getDefaultAvatar("王建国", "teacher")
              },
              createTime: "2024-12-18 17:00:00",
              likes: 25
            },
            {
              id: "r5",
              content: "可以用打电话来类比：三次握手就像打电话时的'喂，听得到吗？''听得到''好的'，四次挥手就像挂电话时的'我要挂了''好的''我也要挂了''好的'。",
                             author: {
                 id: "105",
                 name: "杨志明",
                 role: "student",
                 avatar: getDefaultAvatar("杨志明", "student")
               },
              createTime: "2024-12-18 18:15:00",
              likes: 19
            }
          ],
          tags: ["计算机网络", "TCP", "协议"],
          isPinned: false,
          aiResponse: {
            content: "TCP三次握手和四次挥手是TCP协议建立和断开连接的核心机制，确保数据传输的可靠性。\n\n**三次握手过程：**\n1. 客户端发送SYN包，进入SYN_SENT状态\n2. 服务端收到SYN，发送SYN+ACK包，进入SYN_RCVD状态\n3. 客户端收到SYN+ACK，发送ACK包，双方进入ESTABLISHED状态\n\n**四次挥手过程：**\n1. 主动方发送FIN包，进入FIN_WAIT_1状态\n2. 被动方收到FIN，发送ACK包，进入CLOSE_WAIT状态\n3. 被动方发送FIN包，进入LAST_ACK状态\n4. 主动方收到FIN，发送ACK包，进入TIME_WAIT状态",
            createTime: "2024-12-18 18:30:00"
          }
        }
      ];

      const discussion = mockDiscussions.find(d => d.id === discussionId);
      if (discussion) {
        setDiscussion(discussion);
      } else {
        message.error("讨论不存在");
      }
    } catch (error) {
      message.error("加载讨论详情失败");
      console.error("加载讨论详情失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      const isLiked = likedDiscussions.has(discussion.id);
      
      // 模拟点赞/取消点赞操作
      if (discussion) {
        setDiscussion({
          ...discussion,
          likes: isLiked ? discussion.likes - 1 : discussion.likes + 1
        });
      }
      
      // 通知父组件更新点赞状态
      if (onLikeChange) {
        onLikeChange(discussion.id, !isLiked);
      }
      
      message.success(isLiked ? "取消点赞成功！" : "点赞成功！");
    } catch (error) {
      message.error("操作失败，请重试");
      console.error("点赞操作失败:", error);
    }
  };

  const handleReplyLike = async (replyId: string) => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      // 模拟回复点赞操作
      if (discussion) {
        const updatedReplies = discussion.replies.map(reply => 
          reply.id === replyId 
            ? { ...reply, likes: reply.likes + 1 }
            : reply
        );
        setDiscussion({
          ...discussion,
          replies: updatedReplies
        });
      }
      message.success("点赞成功！");
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  const handleRegenerateAIResponse = async () => {
    if (!user || !discussion) return;

    setAiLoading(true);
    try {
      // 调用AI服务重新生成回复
      const aiRequest = {
        userRole: "student" as const,
        message: `请针对以下讨论问题提供专业的解答和建议：\n\n标题：${discussion.title}\n\n内容：${discussion.content}\n\n标签：${discussion.tags.join(', ')}`,
        context: {
          discussionId: discussion.id,
          title: discussion.title,
          content: discussion.content,
          tags: discussion.tags
        }
      };

      const response = await aiService.chatWithAssistant(aiRequest);
      
      // 更新AI回复
      setDiscussion({
        ...discussion,
        aiResponse: {
          content: response.reply,
          createTime: new Date().toLocaleString(),
          status: "completed" as const
        }
      });

      message.success("AI回复已重新生成");
    } catch (error) {
      console.error("AI回复重新生成失败:", error);
      message.error("AI回复重新生成失败，请稍后重试");
    } finally {
      setAiLoading(false);
    }
  };

  const handleReply = async () => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      const values = await replyForm.validateFields();
      
      // 模拟添加回复
      const newReply: DiscussionReply = {
        id: `r${Date.now()}`,
        content: values.content,
        author: {
          id: String(user.id),
          name: user.name,
          role: user.role,
          avatar: getDefaultAvatar(user.name, user.role)
        },
        createTime: new Date().toLocaleString('zh-CN'),
        likes: 0
      };

      if (discussion) {
        setDiscussion({
          ...discussion,
          replies: [...discussion.replies, newReply]
        });
      }
      
      replyForm.resetFields();
      message.success("回复成功！");
    } catch (error) {
      if (error instanceof Error) {
        message.error("回复失败，请重试");
        console.error("回复失败:", error);
      }
    }
  };

  if (loading) {
    return (
      <StyledModal
        title="讨论详情"
        open={true}
        onCancel={onClose}
        footer={null}
        width={800}
      >
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <div>加载中...</div>
        </div>
      </StyledModal>
    );
  }

  if (!discussion) {
    return null;
  }

  return (
    <StyledModal
      title="讨论详情"
      open={true}
      onCancel={onClose}
      footer={null}
      width={800}
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        <Title level={4}>{discussion.title}</Title>
        <Space>
          <Avatar 
            src={discussion.author.avatar} 
            icon={<UserOutlined />}
          />
          <Text>{discussion.author.name}</Text>
          <Tag
            color={discussion.author.role === "teacher" ? "blue" : undefined}
          >
            {discussion.author.role === "teacher" ? "教师" : "学生"}
          </Tag>
          <Text type="secondary">发布于 {discussion.createTime}</Text>
        </Space>

        <Space>
          {discussion.tags.map((tag) => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </Space>

        <Paragraph>{discussion.content}</Paragraph>

        <Space>
          <Tooltip title={
            user 
              ? (likedDiscussions.has(discussion.id) ? "取消点赞" : "点赞")
              : "登录后即可点赞"
          }>
            <Button
              type="text"
              icon={likedDiscussions.has(discussion.id) ? <LikeFilled /> : <LikeOutlined />}
              onClick={handleLike}
              disabled={!user}
              style={{ 
                color: likedDiscussions.has(discussion.id) ? "#ff4d4f" : "#666"
              }}
            >
              {discussion.likes}
            </Button>
          </Tooltip>
        </Space>

        {discussion.aiResponse && (
          <AIReply>
            <Space align="start">
              <Avatar
                icon={<RobotOutlined />}
                style={{ backgroundColor: "#722ed1" }}
              />
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                  <div>
                    <Text strong>AI助手</Text>
                    <Text type="secondary" style={{ marginLeft: 8 }}>
                      回复于 {discussion.aiResponse.createTime}
                    </Text>
                  </div>
                  {user && discussion.author.id === String(user.id) && (
                    <Tooltip title="重新生成AI回复">
                      <Button
                        type="text"
                        size="small"
                        icon={<RobotOutlined />}
                        loading={aiLoading}
                        onClick={() => handleRegenerateAIResponse()}
                      >
                        重新生成
                      </Button>
                    </Tooltip>
                  )}
                </div>
                <Paragraph style={{ margin: 0, whiteSpace: 'pre-line' }}>
                  {discussion.aiResponse.content}
                </Paragraph>
              </div>
            </Space>
          </AIReply>
        )}

        <Divider orientation="left">全部回复</Divider>

        <ReplyList
          itemLayout="vertical"
          dataSource={discussion.replies}
          renderItem={(reply: DiscussionReply) => (
            <List.Item
              key={reply.id}
              actions={[
                <Tooltip key="like" title={user ? "点赞" : "登录后即可点赞"}>
                  <Button
                    type="text"
                    icon={<LikeOutlined />}
                    onClick={() => handleReplyLike(reply.id)}
                    disabled={!user}
                  >
                    {reply.likes}
                  </Button>
                </Tooltip>,
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Avatar 
                    src={reply.author.avatar} 
                    icon={<UserOutlined />}
                  />
                }
                title={
                  <Space>
                    <Text>{reply.author.name}</Text>
                    <Tag
                      color={
                        reply.author.role === "teacher" ? "blue" : undefined
                      }
                    >
                      {reply.author.role === "teacher" ? "教师" : "学生"}
                    </Tag>
                    <Text type="secondary">回复于 {reply.createTime}</Text>
                  </Space>
                }
                description={reply.content}
              />
            </List.Item>
          )}
        />

        {user && (
          <Form form={replyForm} style={{ marginTop: 24 }}>
            <Form.Item
              name="content"
              rules={[{ required: true, message: "请输入回复内容" }]}
            >
              <TextArea
                placeholder="写下你的回复..."
                autoSize={{ minRows: 2, maxRows: 6 }}
                maxLength={500}
                showCount
              />
            </Form.Item>
            <Form.Item style={{ textAlign: "right", marginBottom: 0 }}>
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleReply}
              >
                发表回复
              </Button>
            </Form.Item>
          </Form>
        )}
      </Space>
    </StyledModal>
  );
};

export default DiscussionDetail;
